package com._520it.crm.service.impl;

import com._520it.crm.domain.Permission;
import com._520it.crm.mapper.PermissionMapper;
import com._520it.crm.service.IPermissionService;
import com._520it.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    private RequestMappingHandlerMapping rmhm;

    @Override
    public int deleteByPrimaryKey(Long id) {
        return permissionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Permission record) {
        return permissionMapper.insert(record);
    }

    @Override
    public Permission selectByPrimaryKey(Long id) {
        return permissionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Permission record) {
        return permissionMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Permission> queryPageResultByRoleId(Long roleId) {
        return  permissionMapper.queryPageResultByRoleId(roleId);
    }

    @Override
    public void reload() {
        //查找数据库中所有的权限
        List<Permission> permissions = permissionMapper.selectAll();
        List<String> resourecs = new ArrayList<>();
        for (Permission permission : permissions) {
            resourecs.add(permission.getExpression());
        }
        System.out.println("-----------------");
        System.out.println(rmhm);
        Map<RequestMappingInfo, HandlerMethod> methods = rmhm.getHandlerMethods();
        for (HandlerMethod method : methods.values()) {
            RequiresPermissions rp = method.getMethodAnnotation(RequiresPermissions.class);
            if (rp!=null){

                Permission permission = new Permission();
                String resource = rp.value()[0];
                if (!resourecs.contains(resource)){
                    String name = method.getMethodAnnotation(PermissionName.class).value();
                    permission.setName(name);
                    permission.setExpression(resource);
                    permissionMapper.insert(permission);
                }
            }
        }
    }

    @Override
    public List<String> queryPermissionsByEmpId(Long id) {
        return permissionMapper.queryPermissionsByEmpId(id);
    }
}
